document.addEventListener('DOMContentLoaded', function() {
    loadCategories();
    const addTypeForm = document.getElementById('add-type-form');
    addTypeForm.addEventListener('submit', function(event) {
        event.preventDefault();
        addCategory();
    });
});

function loadCategories() {
    fetch('/blog/text/listType')
        .then(response => response.json())
        .then(data => {
            if (data.code === 1) {
                const categoryList = document.getElementById('category-list');
                categoryList.innerHTML = ''; // 清空当前分类列表
                data.data.forEach(category => {
                    const categoryDiv = document.createElement('div');
                    categoryDiv.className = 'category-item';
                    categoryDiv.innerHTML = `
                    <span>${category}</span>
                    <button onclick="deleteCategory('${category}')">删除</button>
                `;
                    categoryList.appendChild(categoryDiv);
                });
            } else {
                alert('加载分类失败：' + data.msg);
            }
        })
        .catch(error => {
            alert('请求失败：' + error.message);
        });
}

function addCategory() {
    const typeName = document.getElementById('type-name').value;

    fetch('/blog/user/addType', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ typeName })
    })
        .then(response => response.json())
        .then(data => {
            const addTypeResponse = document.getElementById('add-type-response');
            if (data.code === 1) {
                addTypeResponse.textContent = '分类添加成功';
                addTypeResponse.style.color = 'green';
                loadCategories(); // 重新加载分类列表
            } else {
                addTypeResponse.textContent = '分类添加失败：' + data.msg;
                addTypeResponse.style.color = 'red';
            }
        })
        .catch(error => {
            const addTypeResponse = document.getElementById('add-type-response');
            addTypeResponse.textContent = '请求失败：' + error.message;
            addTypeResponse.style.color = 'red';
        });
}

function deleteCategory(category) {
    fetch(`/blog/user/deleteType/${category}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.code === 1) {
                alert('分类删除成功');
                loadCategories(); // 重新加载分类列表
            } else {
                alert('分类删除失败：' + data.msg);
            }
        })
        .catch(error => {
            alert('请求失败：' + error.message);
        });
}
